<template>
  <div class="box">
    <div id="container">
    </div>
    <div id="panel"></div>
    <div class="action">
      <ul>
        <li>
          <el-select v-model="value" placeholder="请选择级别" size="mini" @change="selectLeve()" style="width:120px;margin-left:10px;">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-input v-model="cityName" placeholder="输入城市名" size="mini" @change="searchBound()" style="width:100px;margin-left:10px;"></el-input>
          <el-button type="primary" size="mini" style="width:50px;margin-left:10px;" @click="searchBound()">搜索</el-button>
        </li>
        <li class="line">
          <el-input v-model="startName" placeholder="输入城市名" size="mini" style="width:100px;margin-left:10px;"></el-input>
          <el-input v-model="endName" placeholder="输入城市名" size="mini" style="width:100px;margin-left:10px;"></el-input>
          <el-button type="primary" size="mini" style="margin-left:10px;" @click="getDrive()">路线规划</el-button>
          <br />
          <el-input v-model="startCity" placeholder="城市" size="mini" style="width:100px;margin-left:10px;"></el-input>
          <el-input v-model="endCity" placeholder="城市" size="mini" style="width:100px;margin-left:10px;"></el-input>
        </li>

      </ul>
    </div>
  </div>
</template>
<script>
export default {
  name: 'maps',
  data () {
    return {
      startCity: '南京',
      endCity: '南京',
      startName: '南京南站',
      endName: '南京站',
      cityName: '南京',
      value: '',
      map: null,
      circle: [],
      marker: [],
      getLayers: [],
      weather: '',
      temperature: '',
      imgUrl: '',
      geolocation: '',
      district: null,
      polygons: [],
      options: [
        {
          value: 'district',
          lable: 'district'
        },
        {
          value: 'city',
          lable: 'city'
        },
        {
          value: 'province',
          lable: 'province'
        }
      ],
      lineResult: null,
      driving: [],
      disCountry: null,
      mask: []
    }
  },
  mounted () {
    //普通地图
    // this.initMap() 
    //定位
    this.getLocation()
    //加载掩模
    this.getYanmo()
  },
  methods: {
    initMap () {
      //初始化地图对象，加载地图
      this.map = new AMap.Map("container", {
        center: [118.769784, 31.932419],//地图中心点
        zoom: 10 //地图显示的缩放级别
      });
      AMap.plugin([
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.OverView',
        'AMap.MapType',
        'AMap.Geolocation',
      ], () => {
        console.log(this.map);
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        this.map.addControl(new AMap.ToolBar());

        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        this.map.addControl(new AMap.Scale());

        // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
        this.map.addControl(new AMap.OverView({ isOpen: true }));

        // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
        this.map.addControl(new AMap.MapType());

        // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
        this.map.addControl(new AMap.Geolocation());
      });
      // this.drawBounds();
      this.getLocation()
    },

    // 掩模
    getYanmo () {
      AMap.plugin("AMap.DistrictSearch", () => {
        var opts = {
          subdistrict: 0,   //返回下一级行政区
          extensions: 'all',  //返回行政区边界坐标组等具体信息
        };
        var district = new AMap.DistrictSearch(opts);
        district.search('江苏', (status, result) => {
          var bounds = result.districtList[0].boundaries;
          console.log('bounds', bounds);
          this.$nextTick(() => {
            if (bounds.length > 0) {
              for (var i = 0; i < bounds.length; i += 1) {
                this.mask.push([bounds[i]])
              }
            }
          })
          console.log('this.mask', this.mask);
          AMap.plugin("AMap.DistrictLayer", () => {
            this.disCountry = new AMap.DistrictLayer.World({
              zIndex: 1,
              rejectMapMask: true
            })
          })
          this.map = new AMap.Map('container', {
            mask: this.mask,
            center: [120.16263, 33.348176],

            viewMode: '3D',
            labelzIndex: 130,
            zoom: 7,
            cursor: 'pointer',
            layers: [
              new AMap.TileLayer.RoadNet({
                zIndex: 7
              }),
              this.disCountry,
              new AMap.TileLayer.Satellite()
            ]
          });
        })
      })
    },

    getLocation () {
      AMap.plugin("AMap.Geolocation", function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 2000
        });

        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete);
        AMap.event.addListener(geolocation, "error", onError);

        function onComplete (data) {
          // data是具体的定位信息  精准定位
          // console.log('定位', data);

        }

        function onError (data) {
          // 定位出错    非精准定位
          // console.log(data);
        }
      });

      /* 获取天气 */
      AMap.plugin('AMap.Weather', function () {
        //创建天气查询实例
        var weather = new AMap.Weather();

        //执行实时天气信息查询
        weather.getLive('南京', function (err, data) {
          // console.log('err', err);
          // console.log('data', data);
        });
      });

      /* 公交站点查询 */
      AMap.plugin(["AMap.StationSearch"], function () {
        //实例化公交站点查询类
        var station = new AMap.StationSearch({
          pageIndex: 1, //页码，默认值为1
          pageSize: 10, //单页显示结果条数，默认值为20，最大值为50
          city: '010' //限定查询城市，可以是城市名（中文/中文全拼）、城市编码，默认值为『全国』
        });

        //执行关键字查询
        station.search('南京南站', function (status, result) {
          //打印状态信息status和结果信息result
          //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误。
          // console.log('公交信息', result);
        });
      });


      /* 查询公交线路 */
      AMap.plugin(["AMap.LineSearch"], function () {
        //实例化公交线路查询类
        var linesearch = new AMap.LineSearch({
          pageIndex: 1, //页码，默认值为1
          pageSize: 1, //单页显示结果条数，默认值为20，最大值为50
          city: "南京", //限定查询城市，可以是城市名（中文/中文全拼）、城市编码，默认值为『全国』
          extensions: "all" //是否返回公交线路详细信息，默认值为『base』
        });

        //执行公交路线关键字查询
        linesearch.search('13路', function (status, result) {
          //打印状态信息status和结果信息result
          // console.log('公交线路', result);
        });
      });

      /* 根据坐标查询地址 */
      AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: '010'
        })

        var lnglat = [118.856371, 32.005985]

        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // result为对应的地理位置详细信息
            // console.log('坐标查询的地址', result);
          }
        })
      }),

        /* 行政区 */
        AMap.plugin('AMap.DistrictSearch', function () {
          var districtSearch = new AMap.DistrictSearch({
            // 关键字对应的行政区级别，country表示国家
            level: 'country',
            //  显示下级行政区级数，1表示返回下一级行政区
            subdistrict: 1
          })

          // 搜索所有省/直辖市信息
          districtSearch.search('中国', function (status, result) {
            // 查询成功时，result即为对应的行政区信息
            // console.log('行政区', result);
          })
        })
    },

    /* 行政区 */
    drawBounds () {
      //加载行政区划插件

      AMap.plugin('AMap.DistrictSearch', () => {
        if (!this.district) {
          //实例化DistrictSearch
          var opts = {
            subdistrict: 0,   //获取边界不需要返回下级行政区
            extensions: 'all',  //返回行政区边界坐标组等具体信息
            level: 'district'  //查询行政级别为 市
          };
          this.district = new AMap.DistrictSearch(opts);
        }
        // console.log(this.district);
        this.district.setLevel(this.value)
        this.district.search(this.cityName, (status, result) => {
          this.map.remove(this.polygons)//清除上次结果
          this.polygons = [];
          var bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              var polygon = new AMap.Polygon({
                strokeWeight: 1,
                path: bounds[i],
                fillOpacity: 0.4,
                fillColor: '#80d8ff',
                strokeColor: '#0091ea'
              });
              this.polygons.push(polygon);
            }
          }
          this.map.add(this.polygons)
          this.map.setFitView(this.polygons);//视口自适应
          console.log(bounds);
        })

      })
    },
    /* 选择级别 */
    selectLeve () {
      console.log(this.value);
    },
    /* 输入城市名 */
    searchBound () {
      console.log(this.cityName);
      // this.drawBounds()
    },
    /* 路线规划 */
    getDrive () {

      this.lineResult = []
      AMap.plugin('AMap.Driving', () => {
        this.driving = new AMap.Driving({
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          policy: AMap.DrivingPolicy.LEAST_TIME,
          map: this.map,
          panel: "panel"
        })
        const dr = this.map.getAllOverlays();
        this.map.clearMap();
        // this.drawBounds()
        var points = [
          { keyword: this.startName, city: this.startCity },
          { keyword: this.endName, city: this.endCity }
        ]
        if (this.driving) {
          this.driving.clear();
          if (this.driving.render) {
            this.driving.render.clear()
          }
        }
        this.lineResult = []
        this.driving.search(points, (status, result) => {
          console.log(result);
          this.lineResult = result
        })
      })
    }
  }
}
</script>
<style  scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100vh;
  background-color: rgb(119, 194, 216);
}
.action {
  position: absolute;
  top: 10px;
  left: 70px;
  text-align: center;
  background-color: rgba(14, 14, 14, 0.644);
  padding: 3px 5px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #424141;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.action ul li {
  text-align: left;
  cursor: pointer;
  /* height: 35px; */
  line-height: 35px;
  color: rgb(233, 233, 233);
  padding: 5px 0;
  border-bottom: 1px rgb(255, 255, 255) solid;
}
.action ul li:hover {
  color: rgb(232, 238, 243);
}
.line {
  position: relative;
}
.line-model {
  position: absolute;
  box-sizing: border-box;
  top: 42px;
  width: 320px;
  height: 500px;
  overflow: auto;
  background-color: #fff;
  border: 1px #ccc solid;
  color: #424141;
  padding: 10px;
}
.icon-chahao {
  position: absolute;
  right: 5px;
  top: 0;
}
.line-action {
  font-size: 12px;
}
#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}
#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}
#panel .amap-lib-driving {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}
</style>>
 
